package com.mocha.bss.domain.rbac.config;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.coffee.core.CoffeeResponse;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: songkui
 * @since: 2022/4/12 17:59
 */
@Service
@Slf4j
@AllArgsConstructor
public class RPCHandler {
    private final DiscoveryClient discoveryClient;
    private final RestTemplate restTemplate;
    private final MochaServerProperties mochaServerProperties;

    //角色功能权限 远程调用 需要的 server 目前只有 gateway
    //TODO 当 角色和 功能权限 发生关系的时候 需要调用
    public void functionRoleServerAPI(){
        String servers = mochaServerProperties.getFunServer();
        doRPC(servers);
    }


    // 敏感词 远程调用 需要的 server
    public void sensitiveServerAPI(){
        String servers = mochaServerProperties.getSensitiveServer();
        doRPC(servers);
    }

    private void doRPC(String servers){
        if (StrUtil.isEmpty(servers)){
            return;
        }

        String[] serverArray = servers.split(",");
        for (String server : serverArray){
            if (StrUtil.isNotBlank(server)){
                List<String> urlList = buildUrl(server);
                if (CollectionUtil.isNotEmpty(urlList)){
                    for (String url : urlList){
                        log.info("*** RPC RUL: {}", url);
                        restTemplate.getForEntity(url, CoffeeResponse.class);
                    }
                }
            }
        }
    }

    private List<String> buildUrl(String server){
        if (StrUtil.isEmpty(server)){
            return null;
        }
        String[] serverInfo = server.split(":");
        if (StrUtil.isEmpty(serverInfo[0]) || StrUtil.isEmpty(serverInfo[1])){
            return null;
        }

        List<ServiceInstance> instances = discoveryClient.getInstances(serverInfo[0].trim());
        if (CollectionUtil.isEmpty(instances)){
            return null;
        }

        List<String> urlList = new ArrayList<>(instances.size());

        for (ServiceInstance s : instances){
            String url = String.format("http://%s:%s/%s", s.getHost(), s.getPort(), serverInfo[1]);
            urlList.add(url);
        }

        return urlList;

    }


}
